package com.yangxk.kadmin.common.support;

import com.yangxk.kadmin.common.enumeration.CommonExceptionEnum;
import com.yangxk.kadmin.common.exception.BizException;
import com.yangxk.kadmin.common.exception.ParamException;
import com.yangxk.kadmin.common.util.JsonUtil;
import com.yangxk.kadmin.common.util.StringUtil;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.*;

public class BeanValidator {

    private BeanValidator() {
    }

    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    public static <T> Map<String, String> validate(T t, Class... groups) {
        Validator validator = validatorFactory.getValidator();
        Set validateResult = validator.validate(t, groups);
        if (validateResult.isEmpty()) {
            return Collections.emptyMap();
        } else {
            LinkedHashMap errors = new LinkedHashMap();
            Iterator iterator = validateResult.iterator();
            while (iterator.hasNext()) {
                ConstraintViolation violation = (ConstraintViolation)iterator.next();
                errors.put(violation.getPropertyPath().toString(), violation.getMessage());
            }
            return errors;
        }
    }

    public static Map<String, String> validateList(Collection<?> collection) {
        if (collection == null || collection.isEmpty()) {
            return Collections.emptyMap();
        }
        Iterator iterator = collection.iterator();
        Map errors;

        do {
            if (!iterator.hasNext()) {
                return Collections.emptyMap();
            }
            Object object = iterator.next();
            errors = validate(object, new Class[0]);
        } while (errors.isEmpty());

        return errors;
    }

    public static Map<String, String> validateObject(Object first, Object... objects) {
        if (objects != null && objects.length > 0) {
            return validateList(Arrays.asList(first, objects));
        } else {
            return validate(first, new Class[0]);
        }
    }

    public static void check(Object param) {
        // 如果param为null则说明没有传递参数，属于服务器异常
        if (param == null)
            throw new BizException(CommonExceptionEnum.ERROR);

        Map<String, String> map = BeanValidator.validateObject(param);
        if (map != null && !map.isEmpty()) {
            String[] msg = new String[map.size()];
            int i = 0;
            for (Map.Entry<String, String> entry : map.entrySet()) {
                msg[i] = entry.getValue();
                i++;
            }
            throw new ParamException(StringUtil.arr2String(msg));
        }
    }
}
